package com.teichmann.core.targets.online;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.teichmann.bo.Car;
import com.teichmann.bo.Seller;
import com.teichmann.core.OnlinePage;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;
import com.teichmann.core.util.CrawlerUtils;

@Url(value = OnlinePage.MEUCARRONOVO_URL+ "/carros/resultado/?buscaAvancada=1&pesq_ddd=51&modeloBusca=")
public class MeuCarroNovo implements OnlinePage {

	Logger logger = Logger.getLogger(this.getClass().getSimpleName());

	private int countCars;
	HttpClient client = ConnectionUtils.getClient();
	ArrayList<Car> cars = new ArrayList<Car>();
	NodeVisitor visitor = new NodeVisitor() {

		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();
			if ("div".equalsIgnoreCase(name)
					&& (tag.getAttribute("id") != null && (tag
							.getAttribute("id").equalsIgnoreCase("result")))) {

				cars.add(extractInformation(tag));
				countCars++;

			}
		}
	};

	public ArrayList<Car> performSearch(String parameter) throws IOException {

		logger.debug("Entering " + this.getClass().getSimpleName());

		String defaultUrl = this.getClass().getAnnotation(Url.class).value()
				+ parameter;
		String responseBody = ConnectionUtils.get(client, defaultUrl);

		String carsFoundString = StringUtils.substringBetween(responseBody,
				"Resultados da Pesquisa &lt;",
				"&gt; Ve&iacute;culos encontrados.");
		int carsFound = carsFoundString != null ? Integer
				.parseInt(carsFoundString.trim()) : 1;
		int numberOfPages = (carsFound / 20) + 1;

		for (int x = 0; x < numberOfPages; x++) {
			responseBody = ConnectionUtils
					.get(client, defaultUrl + "&pag=" + x);

			Parser parser = new Parser(new Lexer(responseBody));
			try {
				parser.visitAllNodesWith(visitor);
			} catch (ParserException e) {
				e.printStackTrace();
			}
		}

		return cars;

	}

	public Car extractInformation(Tag line) {
		Car car = new Car();
		int count = 1;
		try {

			NodeList details = line.getChildren();

			Pattern intOnly = Pattern.compile("\\d+");

			car.setModelo(details.elementAt(3).getChildren().elementAt(3)
					.getChildren().elementAt(0).getText());
			// car.setPlaca(CrawlerUtils.removeUnusedFields(details.elementAt(1).getChildren().elementAt(1).getChildren().elementAt(0).getText()));

			// ano fabricacao
			String anoModelo = CrawlerUtils.removeUnusedFields(details
					.elementAt(3).getChildren().elementAt(9).getChildren()
					.elementAt(0).getText());
			Matcher matcher = intOnly.matcher(anoModelo);
			if (matcher.find()) {
				car.setAnoModelo(new Integer(matcher.group()));
				car.setAnoFabricacao(car.getAnoModelo());
			} else {
				car.setAnoModelo(new Integer(anoModelo));
				car.setAnoFabricacao(car.getAnoModelo());
			}

			car.setCor(CrawlerUtils.removeUnusedFields(details.elementAt(3)
					.getChildren().elementAt(5).getChildren().elementAt(0)
					.getText()));
			car.setCombustivel(CrawlerUtils.removeUnusedFields(details
					.elementAt(3).getChildren().elementAt(7).getChildren()
					.elementAt(0).getText()));

			String url = ((LinkTag) details.elementAt(3)).extractLink();
			car.setUrl(MEUCARRONOVO_URL + url);

			car.setValor(StringUtils.substringAfter(
					CrawlerUtils.removeUnusedFields(details.elementAt(3)
							.getChildren().elementAt(11).getChildren()
							.elementAt(1).getText()), "R$").trim());
			car.setRevenda(new Seller(this.getClass().getSimpleName()));
			
		//	addExtra(car);
			
			

		} catch (Exception e) {
			e.printStackTrace();
		}

		return car;

	}

	private void addExtra(final Car car) throws IOException {
		String responseBody = ConnectionUtils.get(client, car.getUrl());

		
		
		
		Parser parser = new Parser(new Lexer(responseBody));
		try{
	
			
		parser.visitAllNodesWith(new NodeVisitor() {

			@Override
			public void visitTag(Tag tag) {
				
				
				if(car.getFotos()!= null && car.getFotos().size()== 4){
					return;
				}
				
				String name = tag.getTagName();
				if ("img".equalsIgnoreCase(name)
						&& (tag.getAttribute("alt") != null && (tag
								.getAttribute("alt").contains("Clique para Visualizar")))) {

					car.setFotos(car.getFotos() == null ? new ArrayList<String>(): car.getFotos());
					car.getFotos().add(MEUCARRONOVO_URL + tag.getAttribute("src"));
				}
			}
			});
		}
		catch (ParserException e) {
			e.printStackTrace();
		}
		
	}

	public ArrayList<Car> performSearch(String parameter, HttpClient client)throws IOException {
		this.client = client;
		return performSearch(parameter);
	}
	
}
